import { asyncRoutes, constantRoutes } from "@/router"

function hasPermission(authRoutes, route) {
  if (authRoutes && route.name) {
    let has = {
      has: false,
      index: 0
    }
    authRoutes.forEach((item, index) => {
      if (route.name.includes(item.name)) {
        has = {
          has: true,
          index: index
        }
      }
    })
    return has
  } else {
    return {
      has: true,
      index: 0
    }
  }
}

export function filterAsyncRoutes(routes, authRoutes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    let has = hasPermission(authRoutes, tmp).has
    let index = hasPermission(authRoutes, tmp).index
    if (has) {
      if (tmp.children && authRoutes[index].children) {
        tmp.children = filterAsyncRoutes(
          tmp.children,
          authRoutes[index].children
        )
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, authRoutes) {
    return new Promise(resolve => {
      let accessedRoutes
      accessedRoutes = filterAsyncRoutes(asyncRoutes, authRoutes)
      commit("SET_ROUTES", accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
